package com.zmn.oms.admin.controller.work;

import com.google.common.collect.Sets;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.dms.common.enums.coup.ThirdPlatEnum;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.order.OrderBService;
import com.zmn.oms.business.interfaces.part.OrderPartBService;
import com.zmn.oms.business.interfaces.work.OrderWorkBService;
import com.zmn.oms.common.constant.ConfOrderDutyConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderPremissionConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dro.conf.channel.ConfOrderChannelDRO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.customwork.ZsNormalCustomWorkBService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 类描述：工单
 *
 * @author liuying
 * @date 2018/12/10 17:45
 */
public class WorkBaseController extends OmsBaseController {

    @Autowired
    protected OrderWorkService orderWorkService;
    @Autowired
    protected OrderDetailService orderDetailService;
    @Autowired
    protected OrderWorkBService orderWorkBService;
    @Autowired
    protected OrderBService orderBService;
    @Autowired
    protected ZsNormalOrderBService zsNormalOrderBService;
    @Autowired
    protected ZsNormalCustomWorkBService zsNormalCustomWorkBService;
    @Autowired
    protected ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    protected OrderFactoryService orderFactoryService;
    @Autowired
    protected OrderPartBService orderPartBService;
    @Autowired
    protected ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;
    @Autowired
    protected OrderDiscountService orderDiscountService;

    /**
     * 订单修改权限
     *
     * @param orderBO 工单信息
     * @param moduleId
     */
    protected Set<String> getUpdateDisabledFields(OrderBO orderBO, Integer moduleId) {
        OrderWork orderWork = orderBO.getOrderWork();
        OrderDetail orderDetail = orderBO.getOrderDetail();

        Set<String> orderDisabledFields;
        if (Objects.equals(orderWork.getSourceType(), OrderConsts.ORDER_SOURCE_TYPE_FACTORY)) {
            // 厂商单
            orderDisabledFields = this.getFactoryOrderDisabledFields(orderWork);
        } else {
            // 普通单
            orderDisabledFields = this.getOrderDisabledFields(orderWork);
        }

        if (Objects.isNull(moduleId)) {
            // 默认呼叫
            moduleId = 550;
        }

        // 获取修改号码权限
        String updateUserPhonePermitUrl = OrderPremissionConsts.getOrderWorkUpdateUserPhonePermitUrl(moduleId);
        if (!StaffAdminService.isPermitted(updateUserPhonePermitUrl)) {
            orderDisabledFields.add("telephone");
            orderDisabledFields.add("telephone2");
            orderDisabledFields.add("telephone3");
        }

        // 获取修改号码权限
        String updateServCategPhonePermitUrl = OrderPremissionConsts.getPermitUrlByModuleId(moduleId, OrderPremissionConsts.UPDATE_WORK_SERV_CATEG);
        if (!StaffAdminService.isPermitted(updateServCategPhonePermitUrl)) {
            orderDisabledFields.add("productId");
            orderDisabledFields.add("productShowType");
            orderDisabledFields.add("showProduct");
            orderDisabledFields.add("product");
        }

        if (Objects.equals(orderWork.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_CC) && StringUtil.isMobile(orderDetail.getTelephone())) {
            // 呼叫录单 第一个电话无法修改
            orderDisabledFields.add("telephone");
        }

        // 非快捷录单 不允许修改渠道单号
        if (!Objects.equals(orderWork.getReceiveEntranceId(), GateTypeConsts.GATE_PLAT_CHAT)) {
            // 呼叫录单 第一个电话无法修改
            orderDisabledFields.add("outerId");
        }

        return orderDisabledFields;

    }

    /**
     * 厂商单修改权限
     *
     * @param orderWork
     * @return
     */
    private Set<String> getFactoryOrderDisabledFields(OrderWork orderWork) {
        Set<String> disabledFields = Sets.newHashSet();
        if (Objects.isNull(orderWork)) {
            return disabledFields;
        }

        int status = orderWork.getStatus();

        // 厂商名称：录入不可修改
        disabledFields.add("factoryId");
        // 保内/外：录入后即不可修改
        disabledFields.add("bizType");

        // 若当前单，有预付款&渠道佣金的新单，不可改为返修单
        if(!NumberUtil.isNullOrZero(orderWork.getChannelPrepayAmount()) || !NumberUtil.isNullOrZero(orderWork.getChannelAmount())){
            disabledFields.add("type");
        }

        // 已上门后，不可勾选 用户不确定预约时间
        if (status >= OrderStatusConsts.WORK_STATUS_VISIT) {
            disabledFields.add("dutyFail");
        }

        // 超过设置的改约操作时间，不可点击操作时间
        if (Objects.nonNull(orderWork.getDutyTime())) {
            boolean isOperateDutyTime = zsOrderWorkScheduleBService.validateOperateDutyTime(orderWork.getPlat(), ConfOrderDutyConsts.TYPE_OPERATION_PLATFORM);
            if (!isOperateDutyTime) {
                disabledFields.add("operateDutyTime");
            }
        }

        // 分公司不可修改
        if (super.isBranchCompany()) {
            // 1、电话01
//            disabledFields.add("telephone");
            // 标准地址：可修改，分公司仅可修改为服务范围内标准
            disabledFields.add("checkServicePoint");
        }

        // 已上门-进行中，不可修改
        if (status >= OrderStatusConsts.WORK_STATUS_VISIT) {
            disabledFields.add("number");
        }

        // 已完成，不可修改
        if (status >= OrderStatusConsts.WORK_STATUS_DISTRIBUTE) {
            disabledFields.add("test");
        }

        return disabledFields;
    }

    /**
     * 普通单修改权限
     *
     * @param orderWork
     * @return
     */
    private Set<String> getOrderDisabledFields(OrderWork orderWork) {

        Set<String> disabledFields = Sets.newHashSet();
        if (Objects.isNull(orderWork)) {
            return disabledFields;
        }

        int status = orderWork.getStatus();

        // 来源渠道：
        // 1，下单平台和服务平台不想等，不可修改
        // 2，线上渠道不可更改，线下渠道可修改，下单平台和服务平台不想等，不可修改
        ConfOrderChannelDRO confOrderChannelDRO = null;
        try {
            confOrderChannelDRO = confOrderChannelBService.getByChannelId(orderWork.getChannelId());
        } catch (OmsBaseException omsBaseException) {
            omsBaseException.printStackTrace();
        }

        if (!Objects.equals(orderWork.getPlat(), orderWork.getPlatWork())
                || (Objects.nonNull(confOrderChannelDRO) && Objects.equals(confOrderChannelDRO.getPlatformType(), GlobalConsts.NO))) {
            disabledFields.add("channelId");
        }

        //啄木鸟/川南环保：仅已录入-进行中可操作：预约失败；
        if (Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_ZMN) || Objects.equals(orderWork.getPlatWork(), GlobalConsts.PLAT_MARK_CNHB)) {
            if (!Objects.equals(status, OrderStatusConsts.WORK_STATUS_INPUT)) {
                disabledFields.add("dutyFail");
            }
        } else {
            // 已上门后，不可勾选 用户不确定预约时间
            if (status >= OrderStatusConsts.WORK_STATUS_VISIT) {
                disabledFields.add("dutyFail");
            }
        }

        // 超过设置的改约操作时间，不可点击操作时间
        if (Objects.nonNull(orderWork.getDutyTime())) {
            boolean isOperateDutyTime = zsOrderWorkScheduleBService.validateOperateDutyTime(orderWork.getPlat(), ConfOrderDutyConsts.TYPE_OPERATION_PLATFORM);
            if (!isOperateDutyTime) {
                disabledFields.add("operateDutyTime");
            }
        }

        // 已上门-进行中，不可修改
        if (status >= OrderStatusConsts.WORK_STATUS_VISIT) {
            disabledFields.add("number");
        }

        // 已领单后，并且后台产品，不能切换产品类型
        if (status >= OrderStatusConsts.WORK_STATUS_TAKE && !NumberUtil.isNullOrZero(orderWork.getProductId())) {
            disabledFields.add("productShowType");
        }

        // 已完成，不可修改
        if (status >= OrderStatusConsts.WORK_STATUS_DISTRIBUTE) {
            disabledFields.add("test");
        }

        // 啄木鸟返修不允许修改渠道
        if (Objects.equals(orderWork.getChannelId(), OrderConsts.CHANNEL_ID_PLAT_REWORK_NEW_ORDER)) {
            disabledFields.add("channelId");
        }

        List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderDiscountList)) {
            // 美团锁券下单不可修改产品
            boolean meituanDiscount = orderDiscountList.stream().anyMatch(e -> Objects.equals(e.getThirdCode(), GlobalConsts.NO) && Objects.equals(e.getThirdCoupPlat(), ThirdPlatEnum.THIRD_COUP_TYPE_MT.getKey()));
            if (meituanDiscount) {
                disabledFields.add("productId");
                disabledFields.add("productShowType");
                disabledFields.add("showProduct");
                disabledFields.add("product");
            }
        }

        return disabledFields;
    }
}
